﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增出库单</title>
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <link href="~/lib/element-plus/index.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        .container {
            width: 95%;
            height: auto;
            border: none;
            border-radius: 0;
            padding: 0;
            box-shadow: none;
        }

        .form-group {
            margin-bottom: 20px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 5px;
        }

        .note-input {
            height: 100px;
        }

        .goods-table {
            margin-top: 16px;
        }

        .total-row {
            font-weight: bold;
        }

        .button-group {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }

        .input-suffix-dots {
            font-size: 22px;
            cursor: pointer;
            user-select: none;
            position: absolute;
            right: 14px;
            top: 50%;
            transform: translateY(-70%);
        }

        .related-order-input:read-only {
            cursor: pointer;
        }

        .user-item.selected {
            background: #e6f7ff;
            color: #409EFF;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 基础信息 -->
        <div class="form-group">
            <h4>基础信息</h4>
            <el-form ref="basicForm" :model="form" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="出库单号" required class="form-item">
                            <el-input v-model="form.delivery_order_id" placeholder="自动获取系统编号" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="出库类型" required class="form-item">
                            <el-select v-model="form.outbound_type" placeholder="请选择">
                                <el-option v-for="item in industryOptions"
                                           :key="item.dictValue"
                                           :label="item.dictLabel"
                                           :value="item.dictValue">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="仓库名称" required class="form-item">
                            <el-select v-model="form.warehouse_id" placeholder="请选择">
                                <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                          
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="text" class="form-item" style="margin-left: 13px;" v-on:click="goToWarehouseManage">设置</el-button>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="出库日期" required class="form-item">
                            <el-date-picker v-model="form.outbound_date" type="date" placeholder="请选择" value-format="YYYY-MM-DD"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="关联单号" class="form-item">
                            <div style="display: flex; align-items: center;">
                                <el-input v-model="form.related_order_no"
                                          placeholder="请输入或点击选择"
                                          :readonly="form.is_related_sales"
                                          class="related-order-input"
                                          v-on:click="handleRelatedOrderInputClick">
                                    <template #suffix>
                                        <span class="input-suffix-dots"
                                              v-if="form.is_related_sales"
                                              v-on:click.stop="handleRelatedOrderInputClick">
                                            ...
                                        </span>
                                    </template>
                                </el-input>
                                <el-checkbox v-model="form.is_related_sales"
                                             label="关联销售单号"
                                             v-on:change="handleRelateSalesOrderChange"
                                             style="margin-left: 10px;"></el-checkbox>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户名称" class="form-item">
                            <el-input v-model="form.customer_name"
                                      placeholder="请选择关联单号自动填充"
                                      readonly
                                      :disabled="form.is_related_sales"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="!form.is_related_sales">
                    <el-col :span="12">
                        <el-form-item label="收货人" class="form-item">
                            <el-input v-model="form.consignee" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系方式" class="form-item">
                            <el-input v-model="form.contact" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-else>
                    <el-col :span="12">
                        <el-form-item label="收货人" class="form-item">
                            <el-input v-model="form.consignee" placeholder="请选择关联单号自动填充" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系方式" class="form-item">
                            <el-input v-model="form.contact" placeholder="请选择关联单号自动填充" readonly></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="经办人" required class="form-item">
                            <div style="display: flex; align-items: center;">
                                <el-input v-model="form.person_in_charge_name"
                                          placeholder="请选择"
                                          readonly
                                          style="flex: 1; margin-right: 8px;">
                                    <template #suffix>
                                        <span class="input-suffix-dots"
                                              v-on:click.stop="openOrgSelectDialog">
                                            ...
                                        </span>
                                    </template>
                                </el-input>
                                <el-input v-model="form.person_in_charge" type="hidden"></el-input>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12"></el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="form.note" type="textarea" placeholder="请输入备注" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 经办人选择弹窗 -->
        <el-dialog v-model="orgSelectDialogVisible"
                   title="选择经办人"
                   width="800px"
                   style="z-index: 9999;">
            <div style="display: flex; gap: 20px; height: 400px;">
                <!-- 部门树区域（左） -->
                <div style="width: 30%;">
                    <el-input v-model="orgSearchKeyword"
                              placeholder="输入部门名称搜索"
                              clearable
                              v-on:keyup.enter="searchOrgTree">
                        <template #append>
                            <el-button type="primary"
                                       v-on:click="searchOrgTree"
                                       icon="Search"
                                       style="padding: 0 15px;">
                                搜索
                            </el-button>
                        </template>
                    </el-input>
                    <el-tree :data="orgTree"
                             :props="{
                                value: 'organizationId',
                                label: 'organizationName',
                                children: 'children'
                             }"
                             v-on:node-click="handleOrgNodeClick"
                             node-key="organizationId"
                             :highlight-current="true"
                             default-expand-all
                             style="height: 350px; overflow-y: auto;">
                    </el-tree>
                </div>
                <!-- 人员列表区域（中） -->
                <div style="width: 35%;">
                    <el-input v-model="userSearchKeyword"
                              placeholder="输入人员名称搜索"
                              clearable
                              v-on:keyup.enter="searchUserList">
                        <template #append>
                            <el-button type="primary"
                                       v-on:click="searchUserList"
                                       icon="Search"
                                       style="padding: 0 15px;">
                                搜索
                            </el-button>
                        </template>
                    </el-input>
                    <div style="height: 350px; overflow-y: auto;">
                        <div v-for="item in userList"
                             :key="item.userId"
                             class="user-item"
                             :class="{ 'selected': selectedUsers.some(u => u.userId === item.userId) }"
                             v-on:click="toggleUserSelection(item)"
                             style="padding: 8px; cursor: pointer; border-bottom: 1px solid #f0f0f0;">
                            {{ item.userName }}
                        </div>
                    </div>
                </div>
                <!-- 已选人员区域（右） -->
                <div style="width: 30%;">
                    <div style="font-weight: bold; margin-bottom: 5px;">已选择 {{ selectedUsers.length }} 人</div>
                    <div style="height: 350px; overflow-y: auto; border: 1px solid #dcdcdc; border-radius: 4px; padding: 8px;">
                        <div v-for="user in selectedUsers"
                             :key="user.userId"
                             style="display: flex; align-items: center; justify-content: space-between; padding: 4px 8px; margin-bottom: 4px; background: #e6f7ff; border-radius: 4px;">
                            <span>{{ user.userName }}</span>
                            <el-button type="text" icon="CircleClose" size="small" v-on:click="removeUser(user)"></el-button>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="cancelUserSelection">取消</el-button>
                    <el-button type="primary" v-on:click="confirmUserSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 关联单据选择弹窗（改造后） -->
        <el-dialog v-model="relatedOrderDialogVisible" :title="currentDialogTitle" width="960px"  >
            <div style="display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 16px;">
                <el-input v-model="relatedOrderSearch.sales_order_no"
                          placeholder="请选择销售单号"
                          clearable
                          style="width: 100%;">
                </el-input>
                <el-select v-model="relatedOrderSearch.document_status"
                           placeholder="请选择单据状态"
                           clearable
                           style="width: 100%;">
                    <el-option label="未出库" value="6"></el-option>
                    <el-option label="部分出库" value="7"></el-option>
                </el-select>
                <el-select v-model="relatedOrderSearch.customer_name"
                           placeholder="请选择客户"
                           clearable
                           style="width: 100%;">
                    <el-option v-for="item in customerOptions" :key="item.value" :label="item.label" :value="item.label"></el-option>
                </el-select>
                <el-select v-model="relatedOrderSearch.sales_person" placeholder="请输入销售负责人" >
                    <el-option v-for="item in personInChargeOptions" :key="item.value" :label="item.label" :value="item.label"></el-option>
                </el-select>
                <!-- 修改后：带三点选择器的只读输入框 -->
                <div style="display: flex; align-items: center;">
                    <el-input v-model="relatedOrderSearch.sales_dept"
                              placeholder="请选择销售部门"
                              readonly
                              style="flex: 1; margin-right: 8px;">
                        <template #suffix>
                            <span class="input-suffix-dots"
                                  v-on:click.stop="openDeptSelectDialog">
                                ...
                            </span>
                        </template>
                    </el-input>
                  
                </div>
                <el-date-picker v-model="relatedOrderSearch.sales_date"
                                type="date"
                                placeholder="请选择销售日期"
                                style="width: 100%;"
                                value-format="YYYY-MM-DD">
                </el-date-picker>
            </div>
            <div style="text-align: right; margin-bottom: 16px;">
                <el-button type="default" v-on:click="resetRelatedOrderSearch">重置</el-button>
                <el-button type="primary" v-on:click="searchRelatedOrders">查询</el-button>
            </div>
            <!-- 表格列调整为示例样式 -->
            <el-table :data="relatedOrderList" border style="width: 100%" v-on:selection-change ="handleRelatedOrderSelection">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="index" label="序号" width="60"></el-table-column>
                <el-table-column prop="sales_order_no" label="销售单号" width="170"></el-table-column>
                <el-table-column prop="document_status" label="单据状态" width="100">
                    <template #default="scope">
                        {{ formatDocumentStatus(scope.row.document_status) }}
                    </template>
                </el-table-column>
                <el-table-column prop="sales_date" label="销售日期" width="120">
                    <template #default="scope">
                        {{ formatDate(scope.row.sales_date) }}
                    </template>
                </el-table-column>
                <el-table-column prop="customer_name" label="客户名称" width="120"></el-table-column>
                <el-table-column prop="sales_department" label="销售部门" width="100"></el-table-column>
                <el-table-column prop="sales_person" label="销售负责人" width="100"></el-table-column>
                <el-table-column prop="prod_num" label="货品数量" width="100" align="right"></el-table-column>
                <el-table-column prop="saleamount" label="销售金额" width="100" align="right"></el-table-column>
            </el-table>
            <!-- 分页调整 -->
            <el-pagination v-on:size-change="handleRelatedOrderSizeChange"
                           v-on:current-change="handleRelatedOrderCurrentChange"
                           :current-page="relatedOrderCurrentPage"
                           :page-sizes="[8, 16, 32,64]"
                           :page-size="relatedOrderPageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="relatedOrderTotal"
                           style="margin-top: 16px; text-align: right;">
            </el-pagination>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="relatedOrderDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmRelatedOrder">确定</el-button>
                </div>
            </template>
        </el-dialog>



        <!-- 销售部门选择弹窗 -->
        <el-dialog v-model="deptSelectDialogVisible"
                   title="选择销售部门"
                   width="600px"
                   style="z-index: 9999;">
            <div style="display: flex; flex-direction: column; height: 400px;">
                <el-input v-model="deptSearchKeyword"
                          placeholder="输入部门名称搜索"
                          clearable
                          v-on:keyup.enter="searchDeptTree">
                    <template #append>
                        <el-button type="primary"
                                   v-on:click="searchDeptTree"
                                   icon="Search"
                                   style="padding: 0 15px;">
                            搜索
                        </el-button>
                    </template>
                </el-input>
                <el-tree :data="deptTree"
                         :props="{
                value: 'organizationId',
                label: 'organizationName',
                children: 'children'
             }"
                         v-on:node-click="handleDeptNodeClick"
                         node-key="organizationId"
                         :highlight-current="true"
                         default-expand-all
                         style="height: 350px; overflow-y: auto;">
                </el-tree>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="cancelDeptSelection">取消</el-button>
                    <el-button type="primary" v-on:click="confirmDeptSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 出库明细 -->
        <div class="form-group">
            <h4>出库明细</h4>
            <div style="margin-bottom: 16px;">
                <el-button type="success" v-on:click="openAddGoodsDialog">添加</el-button>
                <el-button v-on:click="removeGoodsRow">移除</el-button>
            </div>
            <el-table :data="goodsList" border class="goods-table" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" type="index" width="70"></el-table-column>
                <el-table-column prop="product_name" label="货品名称" width="100"></el-table-column>
                <el-table-column prop="product_code" label="货品编号" width="170"></el-table-column>
                <el-table-column prop="product_type" label="货品类型" width="100"></el-table-column>
                <el-table-column prop="specification_model" label="规格型号" width="100"></el-table-column>
                <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="current_inventory" label="当前库存" width="100" align="right"></el-table-column>

                <!-- 关联单号勾选时显示的列 -->
                <template v-if="form.is_related_sales">
                    <el-table-column prop="prod_num" label="销售数量" width="100" align="right"></el-table-column>
                    <el-table-column prop="outbound_num" label="已出库数量" width="100" align="right"></el-table-column>
                    <el-table-column prop="unoutbound" label="未出库数量" width="100" align="right"></el-table-column>
                    <el-table-column label="出库库位" width="100">
                        <template #default="scope">
                            <el-select v-model="scope.row.warehouse_location"
                                       placeholder="请选择"
                                       v-on:change="handleLocationChange(scope.row, scope.$index)">
                                <el-option v-for="item in warehouseLocationOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="本次出库数量" width="180" align="right">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.current_outbound_quantity"
                                             :min="0"
                                           
                                             v-on:change="handleOutboundQuantityChange(scope.row)"
                                             v-on:blur="handleOutboundQuantityChange(scope.row)">
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="selling_unit_price" label="销售单价" width="100" align="right"></el-table-column>
                    <el-table-column prop="sale_amount" label="销售金额" width="100" align="right"></el-table-column>
                </template>

                <!-- 不勾选关联单号时显示的列 -->
                <template v-else>
                    <el-table-column label="出库库位" width="100">
                        <template #default="scope">
                            <el-select v-model="scope.row.warehouse_location"
                                       placeholder="请选择"
                            v-on:change ="handleLocationChange(scope.row, scope.$index)" 
                            >
                                <el-option v-for="item in warehouseLocationOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="outbound_quantity" label="出库数量" width="100" align="right"></el-table-column>
                    <el-table-column prop="unoutbound_quantity" label="出库单价" width="100" align="right"></el-table-column>
                    <el-table-column prop="unoutbound_quantity" label="出库金额" width="100" align="right"></el-table-column>
                </template>

                <el-table-column prop="batch_no" label="批次号" width="100" align="right">
                    <template #default="scope">
                        <el-input v-model="scope.row.batch_no" placeholder="请输入批次号"></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="production_date" label="生产日期" width="100" align="right">
                    <template #default="scope">
                        <el-date-picker v-model="scope.row.production_date"
                                        type="date"
                                        placeholder="请选择生产日期"
                                        value-format="YYYY-MM-DD"></el-date-picker>
                    </template>
                </el-table-column>

                <el-table-column prop="note" label="备注" width="100" align="right">
                    <template #default="scope">
                        <el-input v-model="scope.row.note" placeholder="请输入备注"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                    <template #default="scope">
                        <el-button type="text" style="color: #409EFF;" v-on:click="removeSingleRow(scope.$index)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row class="total-row" style="margin-top: 8px; display: flex; justify-content: space-between; align-items: center;">
                <div>合计</div>
                <div style="display: flex; gap: 20px;">
                    <div v-if="form.is_related_sales">未出库数量：{{ totalUnoutbound }}</div>
                    <div v-if="form.is_related_sales">已出库数量：{{ totalOutbound }}</div>
                    <div>出库种类：{{ goodsList.length }}</div>
                    <div>出库数量：{{ totalCurrentOutbound }}</div>
                    <div v-if="!form.is_related_sales">出库金额：{{ totalOutboundAmount.toFixed(2) }}</div>
                    <div v-if="form.is_related_sales">销售金额：{{ totalAmount.toFixed(2) }}</div>
                </div>
            </el-row>
        </div>

        <!-- 新增：添加货品弹窗 -->
        <el-dialog v-model="addGoodsDialogVisible" title="添加货品" width="800px">
            <div style="margin-bottom: 16px;">
                <span>销售单号：{{ form.related_order_no }}</span>
            </div>
            <div style="display: flex; gap: 16px; margin-bottom: 16px;">
                <el-input v-model="goodsSearchKeyword" placeholder="请输入货品编号/名称" clearable style="width: 200px;"></el-input>
                <el-select v-model="selectedUnit" placeholder="请选择单位" style="width: 150px;">
                    <el-option v-for="item in unitOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <el-button type="default" style="margin-left: auto;" v-on:click="searchGoods">查询</el-button>
                <el-button type="default" v-on:click="() => { goodsSearchKeyword = ''; selectedUnit = ''; }">重置</el-button>
            </div>
            <!-- 添加货品弹窗的表格修改后 -->
            <el-table :data="addGoodsList" border style="width: 100%" v-on:selection-change="(val) => selectedGoods = val">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" type="index" width="60"></el-table-column>
                <el-table-column prop="sales_order_detail_id" label="销售明细id" width="120" v-if="false"></el-table-column>
                <el-table-column prop="product_code" label="货品编号" width="170"></el-table-column>
                <el-table-column prop="product_name" label="货品名称" width="120"></el-table-column>
                <el-table-column prop="specification_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="selling_unit_price" label="销售单价" width="100" align="right"></el-table-column>
                <el-table-column prop="prod_num" label="销售数量" width="100" align="right"></el-table-column>
                <el-table-column prop="saleamount" label="销售金额" width="100" align="right"></el-table-column>
                <el-table-column prop="outbound_num" label="已出库" width="80" align="right"></el-table-column>
                <el-table-column prop="unoutbound" label="未出库" width="80" align="right"></el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="closeAddGoodsDialog">取消</el-button>
                    <el-button type="primary" v-on:click="confirmGoodsSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 操作按钮 -->
        <div class="button-group">
            <el-button v-on:click="goBack">关闭</el-button>
            <el-button v-on:click="saveAsDraft">保存草稿</el-button>
            <el-button v-on:click="saveAndAddNew">保存并新增</el-button>
            <el-button type="primary" v-on:click="save">保存</el-button>
        </div>



    </div>

    <script>
        const { createApp, ref, onMounted, watch } = Vue;
        const app = createApp({
            setup() {
                // 表单基础信息
                const form = ref({
                    delivery_order_id: '',
                    outbound_type: '',
                    warehouse_id: '',
                    outbound_date: '',
                    related_order_no: '',
                    is_related_sales: true,
                    customer_name: '',
                    consignee: '',
                    contact: '',
                    handler: '',
                    note: '',
                    person_in_charge: '',    // 经办人ID
                    person_in_charge_name: '' // 经办人名称，用于页面显示
                });

                 const currentDialogTitle = ref('关联销售单选择'); // 定义弹窗标题变量
                 const selectedUnit = ref(''); // 定义单位选择变量
                        // 销售部门选择弹窗显隐
                const deptSelectDialogVisible = ref(false);
                // 部门树数据
                const deptTree = ref([]);
                // 部门搜索关键词
                const deptSearchKeyword = ref('');
                // 选中的部门
                const selectedDept = ref(null);


                        // 加载部门树
        const loadDeptTree = async () => {
          try {
            const response = await axios.get('/SalesOrder/GetOrganizationTree');
            deptTree.value = response.data;
          } catch (error) {
            console.error('加载部门树失败：', error);
            ElementPlus.ElMessage.error('加载部门树失败');
          }
        };

        // 搜索部门树
        const searchDeptTree = async () => {
          try {
            if (!deptSearchKeyword.value) {
              await loadDeptTree();
            } else {
              const response = await axios.get('/SalesOrder/GetOrganizationTree2', {
                params: { keyword: deptSearchKeyword.value }
              });
              deptTree.value = response.data;
            }
          } catch (error) {
            console.error('搜索部门树失败：', error);
            ElementPlus.ElMessage.error('搜索部门树失败');
          }
        };

        // 部门节点点击事件
        const handleDeptNodeClick = (node) => {
          selectedDept.value = node;
           console.log('选中的部门：', node); // 新增打印，验证节点是否被正确选中
        };

        // 确认选择部门
        const confirmDeptSelection = () => {
          if (selectedDept.value) {
           relatedOrderSearch.value.sales_dept = selectedDept.value.organizationName;
         
            deptSelectDialogVisible.value = false;
          } else {
            ElementPlus.ElMessage.warning('请选择一个部门');
          }
        };

        // 取消选择部门
        const cancelDeptSelection = () => {
          selectedDept.value = null;
         relatedOrderSearch.sales_dept = '';
          deptSelectDialogVisible.value = false;
        };

        // 打开部门选择弹窗
        const openDeptSelectDialog = async () => {
          await loadDeptTree();
          deptSelectDialogVisible.value = true;
        };


                // 人员选择相关变量
                const userList = ref([]); // 人员列表
                const userSearchKeyword = ref(''); // 人员搜索关键词
                const userLoading = ref(false); // 人员搜索加载状态
                const selectedUsers = ref([]); // 已选人员（单选）

                // 部门树形选择相关
                const orgSelectDialogVisible = ref(false);
                const orgTree = ref([]);
                const selectedOrgId = ref(null);
                const orgSearchKeyword = ref('');

                    // 销售负责人下拉框选项
                const personInChargeOptions = ref([]);

                // 货品明细相关
                const goodsList = ref([]);
                const totalUnoutbound = ref(0);
                const totalOutbound = ref(0);
                const totalCurrentOutbound = ref(0);
                const totalAmount = ref(0);
                const totalOutboundAmount = ref(0);

                // 关联销售单弹窗相关
                const relatedOrderDialogVisible = ref(false);
                const relatedOrderSearch = ref({
                            sales_order_no: '',  // 与后端参数名 sales_order_no 一致
                            document_status: '',
                            customer_name: '',
                            sales_person: '',
                            sales_dept: '',
                            sales_date: ''
                });
                const relatedOrderList = ref([]);
                const relatedOrderCurrentPage = ref(1);
                const relatedOrderPageSize = ref(8);
                const relatedOrderTotal = ref(0);
                const selectedRelatedOrder = ref(null);

                // 下拉框选项
                const warehouseOptions = ref([]);
                const warehouseLocationOptions = ref([]);
                const customerOptions = ref([]);
                const industryOptions = ref([]);

                 // 加载所有负责人
                const loadAllPersonInCharge = async () => {
                    try {
                        const res = await axios.get('/SalesOrder/GetAllPersonInCharge');
                        personInChargeOptions.value = res.data.map(item => ({
                            value: item.userId,
                            label: item.userName
                        }));
                    } catch (err) {
                        ElementPlus.ElMessage.error('加载负责人列表失败');
                    }
                };

                // 人员选择逻辑
                const loadUserList = async (orgId) => {
                    try {
                        userLoading.value = true;
                        const response = await axios.get('/SalesOrder/GetUsersByOrgId', {
                            params: { orgId, keyword: userSearchKeyword.value }
                        });
                        userList.value = response.data.map(item => ({
                            userId: item.UserId,
                            userName: item.UserName
                        }));
                    } catch (error) {
                        console.error('加载人员列表失败：', error);
                        ElementPlus.ElMessage.error('加载人员列表失败');
                    } finally {
                        userLoading.value = false;
                    }
                };

                const searchUserList = async () => {
                    if (selectedOrgId.value) {
                        await loadUserList(selectedOrgId.value);
                    }
                };

                const toggleUserSelection = (user) => {
                    const isSelected = selectedUsers.value.some(u => u.userId === user.userId);
                    if (isSelected) {
                        selectedUsers.value = [];
                    } else {
                        selectedUsers.value = [{ ...user }];
                    }
                };

                const removeUser = (user) => {
                    selectedUsers.value = selectedUsers.value.filter(u => u.userId !== user.userId);
                };

                const confirmUserSelection = () => {
                    if (selectedUsers.value.length > 0) {
                        form.value.person_in_charge = selectedUsers.value[0].userId;
                        form.value.person_in_charge_name = selectedUsers.value[0].userName;
                          // 新增：打印经办人信息到控制台
        console.log('选中的经办人ID：', form.value.person_in_charge);
        console.log('选中的经办人名称：', form.value.person_in_charge_name);
        console.log('经办人完整信息：', selectedUsers.value[0]);
                        orgSelectDialogVisible.value = false;
                    } else {
                        ElementPlus.ElMessage.warning('请选择一个经办人');
                    }
                };

                const cancelUserSelection = () => {
                    selectedUsers.value = [];
                    form.value.person_in_charge = '';
                    form.value.person_in_charge_name = '';
                    orgSelectDialogVisible.value = false;
                };

                // 部门树逻辑
                const loadOrgTree = async () => {
                    try {
                        const response = await axios.get('/SalesOrder/GetOrganizationTree');
                        orgTree.value = response.data;
                    } catch (error) {
                        console.error('加载部门树失败：', error);
                        ElementPlus.ElMessage.error('加载部门树失败');
                    }
                };

                const openOrgSelectDialog = async () => {
                    await loadOrgTree();
                    orgSelectDialogVisible.value = true;
                };

                const searchOrgTree = async () => {
                    try {
                        if (!orgSearchKeyword.value) {
                            await loadOrgTree();
                        } else {
                            const response = await axios.get('/SalesOrder/GetOrganizationTree2', {
                                params: { keyword: orgSearchKeyword.value }
                            });
                            orgTree.value = response.data;
                        }
                    } catch (error) {
                        console.error('搜索部门树失败：', error);
                        ElementPlus.ElMessage.error('搜索部门树失败');
                    }
                };

                const handleOrgNodeClick = (node) => {
                    selectedOrgId.value = node.organizationId;
                    loadUserList(node.organizationId);
                };

                // 货品明细逻辑
                watch(goodsList, (newList) => {
                         // 未出库数量合计 = 各货品未出库数量之和
        totalUnoutbound.value = newList.reduce((sum, item) => sum + (item.unoutbound || 0), 0);
        // 已出库数量合计 = 各货品已出库数量之和
        totalOutbound.value = newList.reduce((sum, item) => sum + (item.outbound_num || 0), 0);
        // 本次出库数量合计 = 各货品本次出库数量之和
        totalCurrentOutbound.value = newList.reduce((sum, item) => sum + (item.current_outbound_quantity || 0), 0);
        // 销售金额合计 = 本次出库数量 * 销售单价 之和
        totalAmount.value = newList.reduce((sum, item) => sum + (item.current_outbound_quantity * (item.selling_unit_price || 0) || 0), 0);
                }, { deep: true });


                const removeGoodsRow = () => {
                    const selectedRows = goodsList.value.filter(row => row._checked);
                    if (selectedRows.length === 0) {
                        ElementPlus.ElMessage.warning('请勾选需要移除的货品行');
                        return;
                    }
                    goodsList.value = goodsList.value.filter(row => !row._checked);
                };

                const removeSingleRow = (index) => {
                    goodsList.value.splice(index, 1);
                };




                     // 修改后
        const loadRelatedOrders = async () => {
          try {
           
            const res = await axios.get('/OutboundManagement/GetPagedOutbound', {
              params: {
                currentPage: relatedOrderCurrentPage.value,
                pageSize: relatedOrderPageSize.value,
                // 与后端参数名完全一致，补充所有查询条件
                sales_order_no: relatedOrderSearch.value.sales_order_no,
                document_status: relatedOrderSearch.value.document_status,
                customer_name: relatedOrderSearch.value.customer_name,
                sales_person: relatedOrderSearch.value.sales_person,
                sales_dept: relatedOrderSearch.value.sales_dept,
                sales_date: relatedOrderSearch.value.sales_date
              }
            });
            relatedOrderList.value = res.data.data;
            relatedOrderTotal.value = res.data.total;
          } catch (error) {
            console.error('加载关联销售单列表失败:', error);
            ElementPlus.ElMessage.error('加载销售单失败');
          }
        };


            // 监听关联单号勾选状态，清空相关字段
        watch(() => form.value.is_related_sales, (newVal) => {
          if (!newVal) {
            form.value.customer_name = '';
            form.value.consignee = '';
            form.value.contact = '';
          }
        }, { immediate: true });



                const searchRelatedOrders = () => {
                    relatedOrderCurrentPage.value = 1;
                    loadRelatedOrders();
                };

                               // 修改后
                const resetRelatedOrderSearch = () => {
                  relatedOrderSearch.value = {
                    sales_order_no: '',
                    document_status: '',
                    customer_name: '',
                    sales_person: '',
                    sales_dept: '',
                    sales_date: ''
                  };
                  searchRelatedOrders();
                };

                const handleRelatedOrderSizeChange = (val) => {
                    relatedOrderPageSize.value = val;
                    loadRelatedOrders();
                };

                const handleRelatedOrderCurrentChange = (val) => {
                    relatedOrderCurrentPage.value = val;
                    loadRelatedOrders();
                };

                const handleRelatedOrderRowClick = (row) => {
                    selectedRelatedOrder.value = row;
                };

                        // 新增：记录选中的销售单
                const selectedRelatedOrders = ref([]);
                const handleRelatedOrderSelection = (val) => {
                  selectedRelatedOrders.value = val;
                };


                     // 修改confirmRelatedOrder方法，从选中列表中取数据
        const confirmRelatedOrder = () => {
          if (selectedRelatedOrders.value.length === 0) {
            ElementPlus.ElMessage.warning('请选择一个销售单');
            return;
          }
          const selectedOrder = selectedRelatedOrders.value[0]; // 取第一个选中的销售单
          form.value.related_order_no = selectedOrder.sales_order_no;
          form.value.customer_name = selectedOrder.customer_name;
          form.value.consignee = selectedOrder.customer_name; // 收货人赋值为客户联系人
          form.value.contact = selectedOrder.contact_phone_number; // 联系方式赋值为客户联系电话
          relatedOrderDialogVisible.value = false;
        };


                const formatDocumentStatus = (status) => {
                    const statusMap = {
                        '1': '草稿',
                        '2': '待审核',
                        '3': '驳回',
                        '6': '未出库',
                        '7': '部分出库',
                        '4': '已完成',
                        '5': '未入库',
                        '8': '部分入库'
                    };
                    return statusMap[status] || '未知状态';
                };

                // 其他基础逻辑
                const loadWarehouseOptions = async () => {
                    try {
                        const res = await axios.get('/OutboundManagement/GetAllWarehouses');
                        if (!res.data.success) {
                            ElementPlus.ElMessage.error(res.data.message || '查询仓库失败');
                            return;
                        }
                        warehouseOptions.value = res.data.data.map(item => ({
                            label: item.warehouse_name,
                            value: item.warehouse_id.toString()
                        }));
                    } catch (error) {
                        console.error('加载仓库列表网络错误:', error);
                        ElementPlus.ElMessage.error('网络异常，无法加载仓库数据');
                    }
                };

                const loadCustomerOptions = async () => {
                    try {
                        const response = await axios.get('/SalesOrder/GetCustomerSelectList');
                        customerOptions.value = response.data;
                    } catch (error) {
                        console.error('加载客户列表失败：', error);
                        ElementPlus.ElMessage.error('加载客户列表失败');
                    }
                };

                     const loadWarehouseLocationOptions = async (warehouseId) => {
                        if (!warehouseId) {
                            warehouseLocationOptions.value = []; // 仓库未选择时清空库位
                            return;
                        }
                        try {
                            const res = await axios.get('/OutboundManagement/GetLocationByWarehouseId', {
                                params: { warehouseId: warehouseId }
                            });
                            warehouseLocationOptions.value = res.data; // 绑定动态库位选项
                        } catch (error) {
                            console.error('加载库位失败：', error);
                            ElementPlus.ElMessage.error('无法加载库位，请重试');
                            warehouseLocationOptions.value = [];
                        }
                     };



                              const handleLocationChange = async (row, index) => {
                            const locationId = row.warehouse_location; // 库位ID（数字类型）
                            const productCode = row.product_code; // 当前行的货品编号
                            if (!locationId || !productCode) {
                                row.current_inventory = 0;
                                return;
                            }
                            try {
                                const warehouseId = form.value.warehouse_id;
                                console.log('仓库ID：', warehouseId, '库位ID：', locationId, '货品编号：', productCode);
                                // 调用接口时传递三个参数
                                const res = await axios.get('/OutboundManagement/GetInventoryByTargetSql', {
                                    params: { warehouseId, locationId, productCode }
                                });
                                row.current_inventory = res.data; // 接收int类型的库存数值
                            } catch (error) {
                                console.error('查询库存失败：', error);
                                ElementPlus.ElMessage.error('无法获取库存数据，请重试');
                                row.current_inventory = 0;
                            }
                        };

                                         // 监听仓库选择变化，动态加载库位
                    watch(() => form.value.warehouse_id, (newWarehouseId) => {
                        // 仓库切换时，清空所有行的库位和库存（避免数据残留）
                        goodsList.value.forEach(row => {
                            row.warehouse_location = '';
                            row.current_inventory = 0;
                        });
                        // 加载新仓库的库位
                        loadWarehouseLocationOptions(newWarehouseId);
                    }, { immediate: true }); // 初始加载时执行一次



                const getIndustryDict = async () => {
                    try {
                        const response = await axios.get('/api/Dict/datas/StockoutType');
                        industryOptions.value = response.data;
                    } catch (error) {
                        console.error('获取出库类型字典失败：', error);
                        ElementPlus.ElMessage.error('获取出库类型数据失败');
                    }
                };

                const getOutboundNumber = async () => {
                    try {
                        const res = await axios.post("/NumberingRule/GenerateBusinessNumber",
                            { rule_id: 13 },
                            { headers: { 'Content-Type': 'application/json' } }
                        );
                        if (res.data.success) {
                            form.value.delivery_order_id = res.data.businessNumber;
                        } else {
                            ElementPlus.ElMessage.error(res.data.message || '生成出库单号失败');
                        }
                    } catch (err) {
                        console.error("获取出库单号失败：", err);
                        ElementPlus.ElMessage.error("获取出库单号失败");
                    }
                };


       const commonSave = async (documentStatus) => {
          try {
            // ===================== 表单校验逻辑 =====================
            // 校验出库日期是否填写
            if (!form.value.outbound_date) {
              ElementPlus.ElMessage.warning('请选择出库日期');
              return Promise.reject(); // 校验失败，返回拒绝状态的Promise
            }

            // 校验仓库是否选择
            if (!form.value.warehouse_id) {
              ElementPlus.ElMessage.warning('请选择仓库名称');
              return Promise.reject();
            }



                   // 新增：校验经办人是否选择（核心代码）
        if (!form.value.person_in_charge) {
          ElementPlus.ElMessage.warning('请选择经办人');
          return Promise.reject();
        }

            // 若关联销售单，则必须添加至少一条货品明细
            if (form.value.is_related_sales && goodsList.value.length === 0) {
              ElementPlus.ElMessage.warning('请添加至少一条货品明细');
              return Promise.reject();
            }





            // 出库数量校验（仅关联销售单时需要）
            if (form.value.is_related_sales) {


                   // 1. 查找“本次出库数量≤0”的货品
        const zeroQtyItem = goodsList.value.find(item =>
          // 兼容未输入、输入0或负数的情况
          !item.current_outbound_quantity || item.current_outbound_quantity <= 0
        );
        if (zeroQtyItem) {
          ElementPlus.ElMessage.warning(`货品【${zeroQtyItem.product_name}】的本次出库数量必须大于0`);
          return Promise.reject();
        }


              // 查找是否有出库数量超过未出库数量的货品
              const invalidItem = goodsList.value.find(item =>
                item.current_outbound_quantity > item.unoutbound_quantity
              );
              if (invalidItem) {
                ElementPlus.ElMessage.warning(`货品【${invalidItem.product_name}】的出库数量不能超过未出库数量`);
                return Promise.reject();
              }
            }

            // 打印出库类型ID，用于调试确认是否正确获取
            console.log("出库类型 ID：", form.value.outbound_type);

            // ===================== 组装提交数据 =====================
            // 主表数据（出库单基础信息）
            const outboundData = {
              outbound_order_no: form.value.delivery_order_id, // 出库单号（系统自动生成）
              type_id: form.value.outbound_type, // 出库类型ID（如销售出库、采购退货等）
              warehouse_id: form.value.warehouse_id, // 仓库ID
              date_of_shipment: form.value.outbound_date, // 出库日期
              associated_order_no: form.value.related_order_no, // 关联销售单号（若有）
              handler_id: form.value.person_in_charge, // 经办人ID（关联系统用户）
              note: form.value.note, // 备注信息
              outbound_status: documentStatus, // 单据状态（草稿/正式提交）
              create_by: 4,  //创建人
              is_delete: '0',
            };

            // 明细数据（出库货品列表）
            const detailsList = goodsList.value.map(item => ({
                 product_code: item.product_code, // 货品编号
                curr_stk_out_num: item.current_outbound_quantity, // 本次出库数量
                selling_unit_price: item.selling_unit_price, // 销售单价
                note: item.note, // 备注
                create_by: 4, // 创建人（需替换为实际登录用户ID）
                is_delete: '0', // 是否删除
                saleamount: (item.current_outbound_quantity * (item.selling_unit_price || 0)).toFixed(2) // 销售金额
            }));

            // 打印组装的数据，用于调试确认格式和内容是否正确
            console.log("即将提交的主表数据：", outboundData);
            console.log("即将提交的明细数据：", detailsList);

            // ===================== 提交到后端 =====================
            // 发送POST请求到后端接口，传递主表和明细数据
            const response = await axios.post(
              '/OutboundManagement/AddOutboundOrder', // 后端接口地址
              { Order: outboundData, Details: detailsList }, // 请求体（主表+明细）
              { headers: { 'Content-Type': 'application/json' } } // 明确JSON格式
            );

            // ===================== 处理响应结果 =====================
            if (response.data.success) {
              // 保存成功，显示提示信息
              ElementPlus.ElMessage.success(
                documentStatus === '1' ? '草稿保存成功' : '保存成功'
              );
              return Promise.resolve(); // 返回成功状态的Promise
            } else {
              // 后端返回失败（如业务校验不通过）
              ElementPlus.ElMessage.error(response.data.message || '保存失败');
              return Promise.reject();
            }
          } catch (error) {
            // 捕获异常（如网络错误、接口报错等）
            console.error('保存失败:', error);
            ElementPlus.ElMessage.error('网络异常，请重试');
            return Promise.reject();
          }
        };


                const save = async () => {
                    await commonSave('2').then(() => {
                        window.location.href = '/OutboundManagement/Index';
                    });
                };

                const saveAsDraft = async () => {
                    await commonSave('1').then(() => {
                        window.location.href = '/Outbound/Index';
                    });
                };

                const saveAndAddNew = async () => {
                    await commonSave('2').then(() => {
                        resetForm();
                        getOutboundNumber();
                    });
                };

                const resetForm = () => {
                    form.value = {
                        delivery_order_id: '',
                        outbound_type: '销售出库',
                        warehouse_id: '',
                        outbound_date: '',
                        related_order_no: '',
                        is_related_sales: true,
                        customer_name: '',
                        consignee: '',
                        contact: '',
                        handler: '',
                        note: '',
                        person_in_charge: '',
                        person_in_charge_name: ''
                    };
                    goodsList.value = [];
                };

                const goToWarehouseManage = () => {
                    window.location.href = '/Warehouse/Index';
                };

                const goBack = () => {
                    window.history.back();
                };

                const handleRelatedOrderInputClick = () => {
                    if (form.value.is_related_sales) {
                        relatedOrderDialogVisible.value = true;
                    }
                };

                const handleRelateSalesOrderChange = (val) => {
                    if (!val) {
                        form.value.related_order_no = '';
                    }
                };

                    const formatDate = (dateStr) => {
                      if (!dateStr) return '';
                      // 假设日期格式为 "2025-10-16T00:00:00"，截取前10位（年月日部分）
                      return dateStr.substring(0, 10);
                    };

        // 新增：添加货品弹窗相关（修改后）
        const addGoodsDialogVisible = ref(false);
        const goodsSearchKeyword = ref('');
        const unitOptions = ref([
          { label: '瓶', value: '瓶' },
          { label: '个', value: '个' },
          { label: '台', value: '台' }
        ]);
        const addGoodsList = ref([
          {
            sales_order_detail_id:'',
            product_code: '',
            product_name: '',
            specification_model: '',
            unit: '',
            selling_unit_price: '',
            prod_num: '',
            saleamount: '',
            outbound_num: '',
            unoutbound: ''
          },
          // 其他模拟数据...
        ]);
        const selectedGoods = ref([]);

        const openAddGoodsDialog = async () => { // 这里添加 async
          const res = await axios.get('/OutboundManagement/GetBySalesOrderNo', {
            params: { salesOrderNo: form.value.related_order_no }
          });
           console.log('后端返回的货品数据：', res.data); // 打印数据，确认字段存在
                // 对每条数据计算“未出库数量 = 销售数量 - 已出库数量”
        addGoodsList.value = res.data.map(item => ({
          ...item,
          unoutbound: Number(item.prod_num || 0) - Number(item.outbound_num || 0)
        }));
          addGoodsDialogVisible.value = true;
        };

        const closeAddGoodsDialog = () => {
          addGoodsDialogVisible.value = false;
        };


               // 确认选择货品
        const confirmGoodsSelection = () => {
          if (selectedGoods.value.length === 0) {
            ElementPlus.ElMessage.warning('请选择至少一个货品');
            return;
          }

          selectedGoods.value.forEach(selected => {
            // 按“货品编号 + 规格型号 + 库位”判断是否重复（多维度去重）
            const isDuplicate = goodsList.value.some(item =>
              item.product_code === selected.product_code
            );

            if (isDuplicate) {
              ElementPlus.ElMessage.warning(`货品【${selected.product_name}】已存在，请修改已有行数量`);
            } else {
                   // 核心：计算未出库数量 = 销售数量 - 已出库数量
        const unoutbound = Number(selected.prod_num || 0) - Number(selected.outbound_num || 0);
              // 不存在则新增行，初始化出库数量为0（后续由用户输入或库存联动）
              goodsList.value.push({
                product_code: selected.product_code,
                product_name: selected.product_name,
                specification_model: selected.specification_model,
                unit: selected.unit,
                product_type: selected.product_type_name, // 需与后端字段对齐，若不存在则忽略
                   unoutbound: unoutbound, // 强制转为数字
        current_inventory: Number(selected.current_inventory || 0), // 强制转为数字
                warehouse_location: selected.warehouse_location, // 库位
                selling_unit_price: selected.selling_unit_price, // 销售单价
                current_outbound_quantity: 0, // 本次出库数量初始为0
                sale_amount: 0, // 销售金额初始为0
                 prod_num: selected.prod_num , //销售数量
                outbound_num: selected.outbound_num, // 已出库数量
                 batch_no: '', // 初始化批次号
                 production_date: '', // 初始化生产日期
                  note: selected.note, // 初始化备注字段
              });
            }
          });

          addGoodsDialogVisible.value = false;
        };


               // 监听出库数量变化，校验并计算销售金额
        const handleOutboundQuantityChange = (row) => {

              const currentOutbound = Number(row.current_outbound_quantity || 0);
        const unoutbound = Number(row.unoutbound || 0);
        const currentInventory = Number(row.current_inventory || 0);

        // 校验未出库数量
        if (currentOutbound > unoutbound) {
          ElementPlus.ElMessage.warning(`货品【${row.product_name}】出库数量不能超过未出库数量（${unoutbound}）`);
          row.current_outbound_quantity = 0;
          row.sale_amount = 0;
          return;
        }

        // 校验当前库存
        if (currentOutbound > currentInventory) {
          ElementPlus.ElMessage.warning(`货品【${row.product_name}】出库数量不能超过当前库存（${currentInventory}）`);
          row.current_outbound_quantity = 0;
          row.sale_amount = 0;
          return;
        }

        // 计算销售金额
        row.sale_amount = (currentOutbound * (row.selling_unit_price || 0)).toFixed(2);

        };

        const searchGoods = () => {
          ElementPlus.ElMessage.info(`搜索货品：${goodsSearchKeyword.value}`);
        };


                // 页面初始化
                onMounted(() => {
                    getOutboundNumber();
                    loadWarehouseOptions();
                    loadWarehouseLocationOptions();
                    getIndustryDict();
                    loadCustomerOptions();
                    loadRelatedOrders();
                    loadAllPersonInCharge();
                });

                return {
                    form,
                    warehouseOptions,
                    warehouseLocationOptions,
                    customerOptions,
                    industryOptions,
                    goodsList,
                    totalUnoutbound,
                    totalOutbound,
                    totalCurrentOutbound,
                    totalAmount,
                    
                    removeGoodsRow,
                    removeSingleRow,
                    save,
                    saveAsDraft,
                    saveAndAddNew,
                    goBack,
                    goToWarehouseManage,
                    relatedOrderDialogVisible,
                    relatedOrderSearch,
                    relatedOrderList,
                    relatedOrderCurrentPage,
                    relatedOrderPageSize,
                    relatedOrderTotal,
                    searchRelatedOrders,
                    resetRelatedOrderSearch,
                    handleRelatedOrderSizeChange,
                    handleRelatedOrderCurrentChange,
                    handleRelatedOrderRowClick,
                    confirmRelatedOrder,
                    formatDocumentStatus,
                    totalOutboundAmount,
                    handleRelatedOrderInputClick,
                    handleRelateSalesOrderChange,
                    openOrgSelectDialog,
                    orgTree,
                    handleOrgNodeClick,
                    searchOrgTree,
                    selectedOrgId,
                    orgSearchKeyword,
                    orgSelectDialogVisible,
                    userList,
                    loadUserList,
                    userSearchKeyword,
                    userLoading,
                    searchUserList,
                    confirmUserSelection,
                    toggleUserSelection,
                    removeUser,
                    cancelUserSelection,
                    selectedUsers,
                    formatDate,
                    personInChargeOptions,

                    deptSelectDialogVisible,
                    deptTree,
                    deptSearchKeyword,
                    selectedDept,
                    loadDeptTree,
                    searchDeptTree,
                    handleDeptNodeClick,
                    confirmDeptSelection,
                    cancelDeptSelection,
                    openDeptSelectDialog,
                    selectedRelatedOrders,
                    handleRelatedOrderSelection,

                    addGoodsDialogVisible,
                    goodsSearchKeyword,
                    unitOptions,
                    addGoodsList, // 替换原goodsList
                    selectedGoods,
                    openAddGoodsDialog,
                    closeAddGoodsDialog,
                    confirmGoodsSelection,
                    searchGoods,
                    handleOutboundQuantityChange,
                    currentDialogTitle,
                    selectedUnit,
                    handleLocationChange,
                  
                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>
</html>